package com.iwunu.gateway.service.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.Map;

import org.apache.commons.codec.binary.Base64;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iwunu.gateway.config.ImageFeature;
import com.iwunu.gateway.constant.DeviceReq;
import com.iwunu.gateway.http.HttpNoCertVerifyUtil;
import com.iwunu.gateway.service.ImageFeatureService;
import com.iwunu.gateway.util.RandomUtil;
import com.iwunu.gateway.util.SignUtlis;
import com.iwunu.iot.common.util.ByteTools;

@Service
public class ImageFeatureServiceImpl implements ImageFeatureService {
//	private StringBuffer script = new StringBuffer();
	@Autowired
	ResourceLoader resourceLoader;
	@Autowired
	ImageFeature  imageFeature;
	
	@Override
	public byte[] getImageFeature(byte[] imageData) {
		String requestParam = "";
		String method = "POST";
		String ctimestamp = System.currentTimeMillis() / 1000L + 60 * 60 * 8L + "";
		String cnonce = RandomUtil.getRandom(6);
        String realUrl = imageFeature.getRealUrl() + imageFeature.getUri();
		Resource resource = resourceLoader.getResource("classpath:cacert2048.pem");
		StringBuffer script = new StringBuffer();
		try {
			InputStream is = resource.getInputStream();
			InputStreamReader isr = new InputStreamReader(is);
			BufferedReader br = new BufferedReader(isr);
			String data = null;
			while ((data = br.readLine()) != null) {
				script.append(data.replace("\n", ""));
			}
			br.close();
			isr.close();
			is.close();

		} catch (IOException e) {
			e.printStackTrace();
			
		}
		String imageDataBase64 = "";
		imageDataBase64 = Base64.encodeBase64String(imageData);
		boolean useLombok = false;
		if (useLombok) {
			// 构建请求体，看要请求的接口说明
			DeviceReq deviceReq = DeviceReq.builder().featureVersion(imageFeature.getFeatureVersion()).imageType("jpg")
					.imageBase64(imageDataBase64).firmwareVersion(imageFeature.getFirmwareVersion()).build();
			// 计算签名
			String csign = SignUtlis.sign(ctimestamp, cnonce, deviceReq, requestParam, imageFeature.getUri(), method,imageFeature.getCappKey(),
					script.toString());
			// 发起请求
			return postJson(ctimestamp, cnonce, imageFeature.getCappKey(), csign, deviceReq, realUrl);
		} else {
			Map<String, String> req_map = new HashMap<String, String>();
			req_map.put("featureVersion", imageFeature.getFeatureVersion());
			req_map.put("imageType", "jpg");
			req_map.put("imageBase64", imageDataBase64);
			if (imageFeature.getFirmwareVersion().length() > 0) {
				req_map.put("firmwareVersion", imageFeature.getFirmwareVersion());
			}
			String csign = SignUtlis.sign(ctimestamp, cnonce, JSON.toJSON(req_map), requestParam,  imageFeature.getUri(), method,imageFeature.getCappKey(),
					script.toString());
			return postJson(ctimestamp, cnonce, imageFeature.getCappKey(), csign, JSON.toJSON(req_map),realUrl);
		}
	}

	private static  byte[] postJson(String ctimestamp, String cnonce, String cappKey, String csign, Object reqeustData,
			String url) {
		String bodyJson = JSONObject.toJSONString(reqeustData);
		String result = HttpNoCertVerifyUtil.doPostToJson(url, bodyJson, ctimestamp, cnonce, cappKey, csign);
		JSONObject jsonResult = JSONObject.parseObject(result);
		if (jsonResult.getInteger("code") == 0) {
			String data = jsonResult.getString("data");
			JSONObject jsonData = JSONObject.parseObject(data);
			if (jsonData.getInteger("code") == 0) {
				String featureBase64 = jsonData.getString("feature");
				return Base64.decodeBase64(featureBase64);

			}
		}
		return null;
	}

	private static void base64ToFile(String base64Str, String fileName) {
		byte[] bytes = Base64.decodeBase64(base64Str);
		String imageString = ByteTools.bytes2HexString(bytes);
		System.out.println(imageString);
		System.out.println(imageString.substring(0, 80));
		try (FileOutputStream outputStream = new FileOutputStream(fileName);) {
			outputStream.write(bytes);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

}
